<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>礼包列表</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="format-detection" content="telephone=no">
	<link rel="stylesheet" href="/plugins/layui/css/layui.css" media="all" />
	<link rel="stylesheet" href="//at.alicdn.com/t/font_tnyc012u2rlwstt9.css" media="all" />
</head>
<body>
	<form class="layui-form" action="">
		<table class="layui-table">
			<colgroup>
				<col width="150">
				<col width="200">
				<col>
			</colgroup>
			<thead>
				<tr>
					<th>客户姓名</th>
					<th>手机号码</th>
					<th>选择保单</th>
					<th>预返金额(元)</th>
				</tr>
			</thead>
			<tbody>
				<tr>

					<td id="memberName" data-id=""></td>
					<td id="memberPhone"></td>
					<td id="policyId" data-id=""></td>
					<td id="returnMoney"></td>
				</tr>
			</tbody>
		</table>

		<table class="layui-table">
			<colgroup>
				<col width="150">
				<col width="200">
				<col>
			</colgroup>
			<thead>
				<tr>
					<th>产品类型</th>
					<th>产品名称</th>
					<th>产品单价</th>
					<th>产品描述</th>
					<th>发送数量</th>
					<th>使用期限</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td><select name="city" lay-verify="required" id="category"
						lay-filter="categoryFilter">
							<option value="">--请选择产品类型--</option>
					</select></td>
					<td><select name="city" lay-verify="required" id="product"
						lay-filter="productFilter">
							<option value="">--请选择具体产品--</option>

					</select></td>
					<td id="productPrice"></td>
					<td id="productDesc"></td>
					<td><input type="text" name="count" required
						lay-verify="required||number" placeholder="请输入数量"
						autocomplete="off" class="layui-input"></td>
					<td><select name="city" lay-verify="required" id="expireTime">
							<option value=""></option>
							<option value="1">1年</option>
							<option value="2">2年</option>

					</select></td>
					<td><button class="layui-btn" lay-submit=""
							lay-filter="addProducts">
							<i class="layui-icon">&#xe608;</i> 添加
						</button></td>
				</tr>
			</tbody>
		</table>

		<table class="layui-table">
			<colgroup>
				<col width="150">
				<col width="200">
				<col>
			</colgroup>
			<thead>
				<tr>
					<th>产品类型</th>
					<th>产品名称</th>
					<th>产品单价(元)</th>
					<th>产品描述</th>
					<th>发送数量</th>
					<th>使用期限(年)</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody id="sendList">
				<tr id="emptyRow">
					<td colspan="7" align="center">列表空空的,什么也没有</td>
				</tr>
			</tbody>
		</table>

		<div class="layui-form-item" id="welfareList"></div>
	</form>

	<div align="right" style="padding: 20px">
		<button class="layui-btn" lay-submit="" lay-filter="saveNotSend">暂时保存</button>
		<button class="layui-btn" lay-submit="" lay-filter="sendNow">立即发送</button>

	</div>
	<div></div>
	<script type="text/javascript" src="/plugins/layui/layui.js"></script>
		<script type="text/javascript">
layui.config({
    base: '/js/admin/'
}).extend({
    ajaxExtention: 'ajaxExtention',//加载自定义扩展，每个业务js都需要加载这个ajax扩展
    $tool: 'tool'
}).use(['form', 'layer', 'tree', 'jquery', 'ajaxExtention', '$tool'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        $ = layui.jquery,
        $tool = layui.$tool;

    var queryArgs = $tool.getQueryParam();//获取查询参数
    var id = queryArgs['id'];
    var globalPackId;
    var globalPolicys;
    var globalProducts;
	  form.on('select(policyFilter)', function(data){
		  if(data.value!=''){
			 $("#returnMoney").html(getReturnMoneyById(data.value)) ;
		  }else{
			  $("#returnMoney").html("");
		  }
      }); 
	  
	  form.on('select(categoryFilter)', function(data){
		  if(data.value!=''){
			  $("#product").html("<option value=''>--请选择具体产品--<option>");
			//  form.render();
			  var products=getProductsByCateId(data.value);
			  var productHtml="";
			  for(var i=0;i<products.length;i++){	
				  productHtml += "<option value='"+products[i].id+"'>"+products[i].name+"</option>"
              }  
			 $("#product").append(productHtml) ;
			
		  }else{
			  $("#product").html("");
		  }
		  form.render();
      });
	  
	  form.on('select(productFilter)', function(data){
		  if(data.value!=''){
			 $("#productPrice").html(getProductByProId(data.value).price) ;
			 $("#productDesc").html(getProductByProId(data.value).description) ;
		  }else{
			  $("#productPrice").html("");
			  $("#productDesc").html("");

		  }
		  form.render();
      });
	  
	 // initUserInfo();
	  initProductInfo();
	  initWelfareInfo();
	  initGiftPackageInfo();
     
    /**
     * 初始化用户信息
     * */
     
   
    function getReturnMoneyById(policyId){
    	   for(var i=0;i<globalPolicys.length;i++){	
    		   if(globalPolicys[i].id==policyId){
    			   return globalPolicys[i].returnMoney;
    		   }
    	   }
    }
    
    function getProductsByCateId(cateId){
 	   for(var i=0;i<globalProducts.length;i++){	
 		   if(globalProducts[i].category.id==cateId){
 			   return globalProducts[i].products;
 		   }
 	   }
 	}
    
    function getProductByProId(proId){
  	   for(var i=0;i<globalProducts.length;i++){
  		   var products=globalProducts[i].products;
  		  for(var j=0;j<products.length;j++){
  	  		   if(products[j].id==proId){
  	  			   return products[j];
  	  		   }
  	  	   }
  		  
  	   }
  	}
    
    function getCurrentLinks(){
    	var links = [];
		//礼品列表
 		$("#sendList .valid_tr").each(function() {
			var obj = new Object();
			obj.id=$(this).attr("data-id");
			obj.memberId=$("#memberName").attr("data-id");
			obj.policyId=$("#policyId").attr("data-id");
			obj.productId= $(this).find(".product").attr("data-id");
			obj.count=$(this).find(".c_count").text();
			obj.welfareId= 0;
			obj.usePeriod=$(this).find(".expireTime").attr("data-id");
			obj.packId=globalPackId;
			links.push(obj); 
		});
		
		//地区福利
		var welfares=$("#welfareList").find("input:checked").length;
		if(welfares>0){
			$("#welfareList").find("input:checked").each(function(){
				var obj = new Object();
				obj.id=$(this).attr("link-id");
				obj.memberId=$("#memberName").attr("data-id");
				obj.policyId=$("#policyId").attr("data-id");
				obj.productId= 0;
				obj.count=1;
				obj.welfareId= $(this).attr("data-id");
				obj.usePeriod=1; //地市福利的使用期限默认一年
				obj.packId=0;
				links.push(obj); 
			})
		}
		return links;
    }
    
    	//计算当前 表里元素的总价格
    	
    	function calculate(){
    		var total=0;
    		 if($("#sendList:has(tr)").length==0){
    			 return 0;
    		 }else{
    			 $("#sendList .valid_tr").each(function(){
    				var price= $(this).find(".c_price").html();
    				var count= $(this).find(".c_count").html();
    				total+=price*count;
    			 });
    		 }
    		 return total;
    	}
    	
    	
    function initProductInfo() {
    	var url="/categorys/getAlls"
        $.ajax({
            url:url,
            method:"GET",
         //   dataType:'json',
            success:function (data) {
                var vos = data.data;
                globalProducts=vos;
               var categorysHtml='';
                 for(var i=0;i<vos.length;i++){	
                	 categorysHtml += "<option value='"+vos[i].category.id+"'>"+vos[i].category.name+"</option>"
               }  
               
               $("#category").append(categorysHtml);
                form.render();//重新绘制表单，让修改生效 
            }
        });
    }
    
    function initWelfareInfo() {

    	var url="/welfares/getByRegion";
        $.ajax({
            url:url,
            method:"GET",
         //   dataType:'json',
            success:function (data) {
                var welfares = data.data;
                if(welfares!=null && welfares.length>0){
                	 var html='<label class="layui-form-label">地市福利</label>'+
                     '<div class="layui-input-block">';
                	 for(var i=0;i<welfares.length;i++){	
                		 html += '<input type="checkbox" data-id="'+welfares[i].id+'" link-id="0" title="'+welfares[i].welfareName+'">';
                   		}  
                	 html +='</div>';
                	 $("#welfareList").html(html);
                	 
                }else{
                	 $("#welfareList").html('');
                }
                form.render();//重新绘制表单，让修改生效 
            }
        });
    }
    
    
     function initUserInfo() {
        var queryArgs = $tool.getQueryParam();//获取查询参数
        var id = queryArgs['id'];
        var url = '/members/getById';
        var req = {id:id};
        $.ajax({
            url:url,
            method:"POST",
            data:req,
         //   dataType:'json',
            success:function (data) {
                var datas = data.data;
               $("#memberName").html(datas.name);
               $("#memberName").attr("data-id",datas.id);
               $("#memberPhone").html(datas.phone);
               
               var policyCodehtml='';
               var policys=datas.customerPolicys;
               globalPolicys=policys;
                 for(var i=0;i<policys.length;i++){	
            	   policyCodehtml += "<option value='"+policys[i].id+"'>"+policys[i].code+"</option>"
               }  
               
               $("#policy").append(policyCodehtml);
                form.render();//重新绘制表单，让修改生效 
            }
        });
       
    }
     /* form.on('click(delProduct)', function(data){
    	 alert('haha');
     }); */
     
     $(document).on('click','.delProduct',function(){
    	 $(this).parent().parent().remove();
    	 $("#totalPrice").html("合计:"+calculate()+"元");
    	 if($("#sendList:has('.valid_tr')").length==0){
    		 $("#totalRow").remove();
    		 $("#sendList").html('<tr><td id="emptyRow" colspan="7" align="center">列表空空 的,什么也没有</td></tr>')
    	 	
    	 }
     }); 
     
     form.on("submit(addProducts)", function (data) {
    	 var category= $("#category").find("option:selected").text();
    	 var product= $("#product").find("option:selected").text();
    	 var productId= $("#product").find("option:selected").val();
         var price=$("#productPrice").html();
         var description=$("#productDesc").html();
    	 var count = $("input[name='count']").val();
    	 var expireTimeText=$("#expireTime").find("option:selected").text();
    	 var expireTimeValue=$("#expireTime").find("option:selected").val();
    	 var html='';
    	 html+='<tr class="valid_tr" data-id="0">'+
    	      '<td>'+category+'</td>'+
    	      '<td data-id="'+productId+'" class="product">'+product+'</td>'+
    	      '<td class="c_price">'+price+'</td>'+
    	      '<td>'+description+'</td>'+
    	      '<td class="c_count">'+count+'</td>'+
    	      '<td class="expireTime" data-id="'+expireTimeValue+'">'+expireTimeText+'</td>'+
    	      '<td>'+
    	      '		<button class="layui-btn layui-btn-danger delProduct" type="button">'+
    	      '   		<i class="layui-icon">&#xe640;</i> 删除'+
    	      '		</button>'+
    	      '</td>'+
    	      ' </tr>';
    	      
    	      if($("#emptyRow").length>0){
    	    	  $("#emptyRow").remove();
    	      }
    	//  $("#sendList").append(html);
    	  if($("#totalRow").length==0){
    		  $("#sendList").append('<tr id="totalRow"><td colspan="7" align="center" id="totalPrice"></td></tr>')
    	  }
    	  
    	  $("#sendList tr:last").before(html);
    	  $("#totalPrice").html("合计:"+calculate()+"元");
    	//  alert(calculate());
    	  return false;
     })
     
        var canSave=true;
      form.on("submit(saveNotSend)", function (data) {
    	  if(getCurrentLinks().length==0){
    		  top.layer.msg("列表为空");
    		  return false;
    	  }
    	
    	 if(!canSave){
   			top.layer.msg("请勿重复提交");
       		return false;
       	}

          var links = getCurrentLinks();
          var obj=new Object();
          obj.links=links;
          var data=JSON.stringify(obj);

    	 canSave=false;
    	var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
  		  $.ajax({
	  			cache : false,
	  			type : "POST",
	  			url : '/cardLinks/setGifts',
	  			contentType : 'application/json',
	  			data : data,// json数据
	  			async : true,
	  			success : function(data) {
	  				if(data.code==2000){
	  					top.layer.close(index);
	  					top.layer.msg("保存成功！");
	  					layer.closeAll("iframe");
	  				}else{
	  					top.layer.msg("保存失败！");
	  				}
	  				canSave=true;
          	 		//刷新父页面
          	 		//parent.location.reload();
	  			},
	  			error:function(data){
	  				canSave=true;
	  			}
  			}); 
    	  return false; 
     })
     
      form.on("submit(sendNow)", function (data) {
          var links = getCurrentLinks();
          var obj=new Object();
          obj.links=links;
          var data=JSON.stringify(obj);
    	var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
  		  $.ajax({
	  			cache : false,
	  			type : "POST",
	  			url : '/cardLinks/setGifts',
	  			contentType : 'application/json',
	  			data : data,// json数据
	  			async : false,
	  			success : function(data) {
	  				if(data.code==2000){
	  					var packId=data.data.id;
	  				 	$.ajax({
	  						cache : false,
	  						type : "POST",
	  						data:{id:packId},
	  						url : '/cards/postCard',
	  						async : false,
	  						success : function(data) {
	  							if(data.code==2000){
	  								top.layer.close(index);
		  		  					top.layer.msg("发送成功！");
		  		  					layer.closeAll("iframe");
		  		  					 parent.location.reload();
	  							}else{
	  								top.layer.msg("发送失败！");
	  							}
	  						}
	  				 	})
	  		 
	  				}else{
	  					top.layer.msg("保存失败！");
	  				}
	  				
	  				return false;
          	 		//刷新父页面
          	 		//parent.location.reload();
	  			}
  			}); 
    	  return false;
     })
      
     
    /**
     * 表单提交
     * */
     form.on("submit(editCategorys)", function (data) {
        var queryArgs = $tool.getQueryParam();//获取查询参数
        var id = queryArgs['id'];
        var name = data.field.name;
        //请求
        var url ='/categorys/update';
        var req = {
            id:id,
            name: name,
        };
        $.ajax({
            url: url,
            contentType:"application/json;charset=UTF-8",
            data: JSON.stringify(req),
            method: "post",
            success: function (data) {
                //top.layer.close(index);(关闭遮罩已经放在了ajaxExtention里面了)
             
                	 layer.msg("用户更新成功！", {time: 1000}, function () {
                         layer.closeAll("iframe");
                         //刷新父页面
                         parent.location.reload();
                     });
                
               
            }
           
        });

        return false;
    }) 
    
    
         function initGiftPackageInfo() {
        var queryArgs = $tool.getQueryParam();//获取查询参数
        var id = queryArgs['id'];
        globalPackId=id;
        //var url = '/subscribe/user/'+id;
        var url = '/giftPackages/getById';
        var req = {
            id:id

        };
        
        $.ajax({
            url:url,
            method:"POST",
            data:req,
         //   dataType:'json',
            success:function (data) {
                var member = data.member;
                var policy=data.policy;
                var productDtos=data.productDtos;
                var ownerWelfares=data.ownerWelfares;
               $("#memberName").html(member.name);
               $("#memberName").attr("data-id",member.id);
               $("#memberPhone").html(member.phone);
               if(policy!=null){
            	   $("#policyId").html(policy.code);
            	   $("#policyId").attr("data-id",policy.id);
            	   $("#returnMoney").html(policy.returnMoney);
               }else{
            	   $("#policyId").attr("data-id",0);
            	   $("#policyId").html('无');
            	   
               }
               
             	 var html='';
             	 if(productDtos!=null && productDtos.length>0){
             		for(var i=0;i<productDtos.length;i++){	
             			 html+='<tr class="valid_tr" data-id="'+productDtos[i].linkId+'">'+
               	      '<td>'+productDtos[i].categoryName+'</td>'+
               	      '<td data-id="'+productDtos[i].id+'" class="product">'+productDtos[i].name+'</td>'+
               	      '<td class="c_price">'+productDtos[i].price+'</td>'+
               	      '<td>'+productDtos[i].description+'</td>'+
               	      '<td class="c_count">'+productDtos[i].count+'</td>'+
               	      '<td class="expireTime" data-id="'+productDtos[i].usePeriod+'">'+productDtos[i].usePeriod+'</td>'+
	               	   '<td>'+
	         	      '		<button class="layui-btn layui-btn-danger delProduct" type="button">'+
	         	      '   		<i class="layui-icon">&#xe640;</i> 删除'+
	         	      '		</button>'+
	         	      '</td>'+
               	      ' </tr>';	
             		}
             		 if($("#emptyRow").length>0){
           	    	  $("#emptyRow").remove();
           	      	}
             		if($("#totalRow").length==0){
              		  $("#sendList").append('<tr id="totalRow"><td colspan="7" align="center" id="totalPrice"></td></tr>')
              	  	}
             		
             		 $("#sendList tr:last").before(html);
             		$("#totalPrice").html("合计:"+calculate()+"元");
             	 }
             	 
             	 //选中地市福利
             	 for(var i=0;i<ownerWelfares.length;i++){	
             	$('#welfareList input[data-id='+ownerWelfares[i].welfareId+']').attr('checked', true);
             		// $('#welfareList input["data-id='+ownerWelfares[i]+'"]').attr('checked', true);
             	$('#welfareList input[data-id='+ownerWelfares[i].welfareId+']').attr('link-id', ownerWelfares[i].linkId);
             	 }
             	 
            	     
                form.render();//重新绘制表单，让修改生效 
            }
        });
       
    }

});

</script>


</body>
</html>